package simtester.server

import org.springframework.dao.DataIntegrityViolationException

class TeamController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

	def list() {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[teamInstanceList: Team.list(params), teamInstanceTotal: Team.count()]
	}
	
    def create() {
        if (request.method == 'POST') {
            def team = new Team(name: params.name.toLowerCase())
            team.save()
			def teamlist = team.list().collect { it.name }
            redirect(controller: 'user', action: 'create')
        }
    }


    def update() {
		def updteamlist = params.updatedteamlist.tokenize(',')
		updteamlist = updteamlist.collect { it.toLowerCase() }
        def currlist = Team.list().collect { it.name }

		def tocreate = updteamlist - currlist
		def toremove = currlist - updteamlist

		tocreate.each {
			new Team(name: it.toLowerCase()).save(failOnError: true)
		}
		
		toremove.each {
			Team.findByName(it.toLowerCase()).delete()
		}

        redirect(controller: 'user', action: 'home')
    }

    def delete() {
        def team = Team.get(params.id)
        team.delete()
		return
    }
}
